package com.example.myapplication3;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class MainActivity extends AppCompatActivity {
    private boolean mReceiveThreadRunning = true;
    private static DatagramSocket socket;
    private static final int RECEIVEPORT = 10001;
    private byte[] mReceive = new byte[32];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = findViewById(R.id.text2);


        try {
            socket = new DatagramSocket(RECEIVEPORT);
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                final DatagramPacket dPacket = new DatagramPacket(mReceive, 32);
                while (mReceiveThreadRunning) {
                    try {
                        socket.receive(dPacket);
                        int receiveSize = dPacket.getLength();
                        String receivedData = new String(dPacket.getData(), 0, receiveSize);
                        Log.d("UADTBIKE", "receive " + receiveSize);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                textView.setText("success");
                            }
                        });
                    } catch (IOException e) {
                        Log.d("UADTBIKE", "Something Error");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                textView.setText("failed");
                            }
                        });
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mReceiveThreadRunning = false;
        if (socket != null && !socket.isClosed()) {
            socket.close();
        }
    }

}